package org.common.users.controller;

import org.common.users.annotation.RepeatRequest;
import org.common.users.entity.dto.User1000wDto;
import org.common.users.entity.po.User1000w;
import org.common.users.entity.vo.ResponseData;
import org.common.users.service.IUser1000wService;
import org.common.users.service.impl.RedisService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 所有请求都是通过restful风格定义的
 *
 * @author samphin
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUser1000wService user1000wService;

    @Autowired
    private RedisService redisService;

    /**
     * 从redis中取出姓陈用户信息，并返回到界在，用vue渲染出死表数据。
     */
    @GetMapping("/queryUserInfoForChen/{start}/{end}")
    public List<Object> queryUserInfoForChen(@PathVariable int start, @PathVariable int end) {
        long t1 = System.currentTimeMillis();
        System.out.println("从Redis中开始查询：" + t1);
        List<Object> users = redisService.lRange("user1000w_firstname_chen", 0, 9);
        long t2 = System.currentTimeMillis();
        System.out.println("查询总耗时：" + (t2 - t1) + "，姓陈的用户共有" + users.size() + "条！");
        return users;
    }

    /**
     * 新增用户
     *
     * @return
     */
    @RepeatRequest(repeat = true, check = true)
    @PostMapping
    public ResponseData addUser(@RequestBody User1000wDto dto) {
        try {
            User1000w user = new User1000w();
            BeanUtils.copyProperties(dto, user);
            user1000wService.insert(user);
            return ResponseData.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.failure();
        }
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteUser/{id}")
    public ResponseData delete(@PathVariable int id) {
        try {
            user1000wService.deleteByPrimaryKey(id);
            return ResponseData.success();
        } catch (Exception e) {
            return ResponseData.failure();
        }
    }

    /**
     * 修改
     *
     * @param user
     * @return
     */
    @PutMapping(value = "/updateUser/{user}", produces = "application/json",
            consumes = "application/json")
    public ResponseData update(@RequestBody @Valid User1000w user) {
        try {
            user1000wService.updateByPrimaryKeySelective(user);
            //从redis中查询当前用户信息，如果存在也更新缓存信息。
            return ResponseData.success();
        } catch (Exception e) {
            return ResponseData.failure();
        }
    }
}
